package com.cskaoyan.controller.wx_address;

import com.cskaoyan.bean.PageDataVo;
import com.cskaoyan.bean.user.Address;
import com.cskaoyan.bean.user.User;
import com.cskaoyan.bean.wx_address.AddressVO;
import com.cskaoyan.bean.wx_resp.WxRespVo;
import com.cskaoyan.service.wx_address.WxAddressService;
import com.cskaoyan.utils.Constant;
import com.cskaoyan.utils.ReflectionSetJavaBeanUtils;
import com.cskaoyan.utils.ValidationUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping({"wx/address"})
public class WxAddressController {
    @Autowired
    WxAddressService wxAddressService;

    @GetMapping("list")
    public WxRespVo queryAddressByUserId() {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipals().getPrimaryPrincipal();
        List<AddressVO> addresses = wxAddressService.queryAddressByUserId(user.getId());
        return WxRespVo.ok(PageDataVo.ok(addresses));
    }

    /**
     * 添加地址接收id为0，所有添加失败则id还是0
     *
     * @param address
     * @return
     */
    @PostMapping("save")
    public WxRespVo createAddress(@RequestBody @Validated Address address, BindingResult bindingResult) {
        ValidationUtil.valid(bindingResult);
        if (!address.getTel().matches("^1[0-9]{10}$")) {
            return WxRespVo.error("手机号码必须为11位，并且以1开头");
        }
        ReflectionSetJavaBeanUtils.setUserId(address);
        int id = wxAddressService.createAddress(address);
        if (id==-1)return WxRespVo.error("唯一默认地址，不可移除");
        if (id == 0) return WxRespVo.error();
        return WxRespVo.ok(id);
    }

    @PostMapping("delete")
    public WxRespVo deleteAddress(@RequestBody Map<String, Integer> map) {
        Integer id = map.get("id");
        int code = wxAddressService.deleteAddress(id);
        if (code == Constant.SUCCESS) return WxRespVo.ok();
        return WxRespVo.error("删除失败，默认地址不能删除");
    }

    @GetMapping("detail")
    public WxRespVo queryAddressDetail(Integer id) {
        AddressVO addressVO = wxAddressService.queryAddressDetail(id);
        return WxRespVo.ok(addressVO);
    }
}
